<script setup lang="ts">
import { reactive, ref, unref } from 'vue'
import { formatOptions, formatRowComponents, vxeGridColumnProps } from '@/utils/custom'
import { Close, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { BusinessUIColumnType, FormComponentProp } from '@/types/custom'

const set_json_parse_key = ref('')
const set_json_parse_value = ref('')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<BusinessUIColumnType>({
  field: '',
  title: '',
  set_json: '',
  set_json_parse: { props: {} },
  is_pid: false,
  visible: false,
  is_sort_col: false,
  customer: {
    actions: []
  }
})
const restaurants = ref<FormComponentProp[]>(vxeGridColumnProps)
const rules = reactive<FormRules<TypedAny>>({
  field: [{ required: true, message: '请输入中文名称', trigger: 'blur' }]
})

const open = (column: BusinessUIColumnType) => {
  ruleForm.value = column
}

/**
 * 新增参数
 */
const addProp = () => {
  const keys = Object.keys(ruleForm.value.set_json_parse.props)
  const key = unref(set_json_parse_key)
  const value = unref(set_json_parse_value)
  if (key) {
    if (keys.includes(key)) {
      ElMessage.warning('属性名已存在')
    } else {
      if (key === 'type' && ['checkbox', 'seq'].includes(value)) {
        ruleForm.value.set_json_parse.props.width = '40'
      }

      ruleForm.value.set_json_parse.props[key] = value
    }
  } else {
    ElMessage.warning('请输入属性名')
  }
}

/**
 * 删除参数
 * @param key
 */
const onDeleteProp = (key: string) => {
  delete ruleForm.value.set_json_parse.props[key]
}

/**
 * 查询
 * @param queryString
 * @param cb
 */
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}

const querySearch2List: SelectOptionType[] = []

/**
 * 查询
 * @param queryString
 * @param cb
 */
const querySearch2 = (queryString: string, cb: (results: SelectOptionType[]) => any) => {
  // console.log(queryString)
  // const results: FormComponentProp[] = queryString
  //   ? restaurants.value.filter(createFilter(queryString))
  //   : restaurants.value
  cb(querySearch2List)
}

/**
 * 选择属性附带默认值
 * @param item
 * @param k
 */
const onQuerySelect2 = (item: SelectOptionType, k: string | number | undefined) => {
  ruleForm.value.set_json_parse.props[String(k)] = item.value
}

const setJsonParse = (item: FormComponentProp, tag: string) => {
  set_json_parse_value.value = tag
  set_json_parse_key.value = item.value
}

const onFocus = (x: string, k: string | number | undefined) => {
  console.log('onFocus', x)
  querySearch2List.splice(0)
  const item = vxeGridColumnProps.find((f) => f.value === k)
  if (item && item.values) {
    item.values.forEach((v) => {
      v.values.forEach((k) => {
        querySearch2List.push({
          label: k,
          value: k
        })
      })
    })
  }
}

/**
 * @param queryString
 */
const createFilter = (queryString: string) => {
  return (restaurant: FormComponentProp) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

const onFormatType = (value: string) => {
  if (value && value.indexOf('money') !== -1) {
    ruleForm.value.set_json_parse.formatFixed = 2
  } else {
    ruleForm.value.set_json_parse.formatFixed = undefined
  }
}

defineExpose({ open })
</script>

<template>
  <el-form
    v-if="ruleForm.field"
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="90px"
    status-icon
  >
    <el-row :gutter="35">
      <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
        <el-form-item label="字段" class="mb1" span="24">
          {{ ruleForm.field }}
        </el-form-item>
        <el-form-item label="中文名称" prop="title" class="mb1">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="树形结构" prop="is_pid" class="mb1">
          <el-switch
            v-model="ruleForm.is_pid"
            inline-prompt
            active-text="开启树形结构"
            inactive-text="是否是树形结构"
          />
          <el-checkbox
            v-if="ruleForm.is_pid"
            v-model="ruleForm.set_json_parse.expandAll"
            label="默认展开"
            class="ml10"
          />
          <span class="ml10 color-warning">生成树的父级ID（列如：pid）</span>
        </el-form-item>
        <el-form-item label="表格排序" prop="is_sort_col" class="mb1">
          <div class="flex">
            <el-switch
              v-model="ruleForm.is_sort_col"
              inline-prompt
              active-text="开启排序"
              inactive-text="是否排序"
            />
            <el-select
              v-if="ruleForm.is_sort_col"
              v-model="ruleForm.orderby"
              placeholder="默认排序方式"
              clearable
              style="width: 150px"
              class="ml10"
            >
              <el-option value="asc" label="升序" />
              <el-option value="desc" label="降序" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="审批节点" prop="nodeApp" class="mb1">
          <el-switch
            v-model="ruleForm.set_json_parse.nodeApp"
            inline-prompt
            active-text="审批节点"
            inactive-text="审批节点"
          />
        </el-form-item>
        <el-form-item label="表尾合计" prop="showFooter" class="mb1">
          <el-switch
            v-model="ruleForm.set_json_parse.showFooter"
            inline-prompt
            active-text="合计本列"
            inactive-text="合计本列"
          />
        </el-form-item>
        <el-form-item label="合并行" prop="merge" class="mb1">
          <el-switch
            v-model="ruleForm.set_json_parse.merge"
            inline-prompt
            active-text="开启合并行"
            inactive-text="关闭合并行"
          />
          <span class="ml10 color-warning">只会合并上下文相同的行</span>
        </el-form-item>
        <el-form-item label="主要信息" prop="isTips" class="mb1">
          <el-switch
            v-model="ruleForm.set_json_parse.isTips"
            inline-prompt
            active-text="主要信息"
            inactive-text="主要信息"
          />
          <span class="ml10 color-warning">弹窗提示等显示时使用</span>
        </el-form-item>
        <!--        <el-form-item label="表格显示" prop="is_sort_col" class="mb1">-->
        <!--          <el-switch-->
        <!--            v-model="ruleForm.visible"-->
        <!--            inline-prompt-->
        <!--            active-text="表格显示"-->
        <!--            inactive-text="表格显示"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="格式化类型" prop="formatType" class="mb3">
          <div class="flex align-center flex-grow">
            <el-select
              v-model="ruleForm.set_json_parse.formatType"
              placeholder="格式化配置"
              clearable
              style="width: 200px"
              @change="onFormatType"
            >
              <el-option
                v-for="item in formatOptions.filter((f) => !f.discard)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span class="ml-auto" v-show="ruleForm.set_json_parse.formatType">保留小数</span>
            <el-input-number
              v-show="ruleForm.set_json_parse.formatType"
              v-model="ruleForm.set_json_parse.formatFixed"
              style="width: 120px"
              class="ml5"
            />
          </div>
        </el-form-item>
        <el-form-item label="前/后缀" prop="prefix" class="mb3">
          <div class="flex align-center">
            <span class="flex-shrink">前缀：</span>
            <el-input v-model="ruleForm.set_json_parse.prefix" placeholder="前缀" clearable />
            <span class="flex-shrink ml5">后缀：</span>
            <el-input v-model="ruleForm.set_json_parse.suffix" placeholder="后缀" clearable />
          </div>
        </el-form-item>
        <el-form-item label="行内组件" prop="component">
          <el-select
            v-model="ruleForm.set_json_parse.component"
            placeholder="行内组件"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in formatRowComponents"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover">
          <div class="mb10">
            <div class="text-capitalize mb5 color-info font16">列属性拓展</div>
            <div class="flex align-center">
              <el-autocomplete
                size="small"
                style="width: 40%"
                v-model="set_json_parse_key"
                :fetch-suggestions="querySearch"
                clearable
                placeholder="属性名"
              >
                <template #default="{ item }">
                  <div class="value">
                    <span class="color-primary">{{ item.value }}</span>
                    <span>（{{ item.label }}）</span>
                  </div>
                  <div v-if="item.values" style="line-height: 16px">
                    <div
                      v-for="(row, idx) in item.values"
                      :key="idx"
                      style="max-width: 40vw; white-space: wrap"
                      class="font14"
                    >
                      <i class="font12 color-info">{{ row.title }}：</i>
                      <el-tag
                        size="small"
                        effect="plain"
                        type="warning"
                        class="mr3"
                        v-for="tag in row.values"
                        :key="tag"
                        @click.stop="setJsonParse(item, tag)"
                        >{{ tag }}
                      </el-tag>
                    </div>
                  </div>
                  <div v-else class="color-info" style="white-space: pre; line-height: 20px">
                    {{ item.type }}
                  </div>
                </template>
              </el-autocomplete>
              <el-input
                size="small"
                style="width: 150px"
                v-model="set_json_parse_value"
                placeholder="值"
                class="ml5"
              />
              <el-button type="success" text :icon="Plus" @click="addProp" class="ml5"
                >新增属性
              </el-button>
            </div>
          </div>
          <div v-for="(x, k) in ruleForm.set_json_parse.props" :key="k">
            <div class="flex align-center mb5">
              <div class="flex-shrink" style="width: 40%">{{ k }}</div>
              <!--              <el-input size="small" v-model="ruleForm.set_json_parse.props[k]" placeholder="值"/>-->
              <el-autocomplete
                size="small"
                v-model="ruleForm.set_json_parse.props[k]"
                :fetch-suggestions="querySearch2"
                clearable
                placeholder="值"
                @select="onQuerySelect2($event, k)"
                @focus="onFocus(x, k)"
                class="flex-grow"
              >
                <template #default="{ item }">
                  <span>{{ item.value }}</span>
                </template>
              </el-autocomplete>
              <el-button
                size="small"
                :icon="Close"
                circle
                class="ml10"
                @click="onDeleteProp(String(k))"
              />
            </div>
          </div>
          <template #footer>
            <div class="flex align-center">
              <span class="color-info">columns属性请参阅：</span>
              <el-link href="https://vxetable.cn/#/grid/api" target="_blank" type="primary">
                文档地址
              </el-link>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </el-form>
  <el-empty v-else description="请选择需要配置的列" />
</template>
